﻿using iTool.PluginCore.Server;
using Microsoft.Extensions.Configuration;
using System;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;

namespace iTool.ServerPlugins
{
    [Description("ashdrahsgfdahgsdhagsdfhg")]
    public class SqlServerProvider : ILServerPlugin
    {
        public string Name { get; }

        private readonly IConfiguration configuration;
        public SqlServerProvider(IConfiguration configuration)
        {
            this.Name = "SqlServer111";
            this.configuration = configuration;
        }

        [Description("氨甲环酸大噶就会升高的阿萨的脚后跟就阿桑的歌啊就是的加啊四的")]
        [ExportMethod("Test")]
        public Task<string> ExecuteAsync(string sql, string connectionName, int xxx)
        {
            return Task.FromResult(sql + connectionName + xxx + "asdasdasd");
        }

        /// <summary>
        /// insert update  delete
        /// </summary>
        /// <param name="MSSQLHost"></param>
        /// <param name="User"></param>
        /// <param name="Password"></param>
        /// <param name="sqlCreateDBQuery"></param>
        /// <returns></returns>
        [ExportMethod("Execute")]
        public async Task<int> ExecuteAsync(string sql, string connectionName)
        {
            using (SqlConnection connection = new SqlConnection(this.configuration.GetConnectionString(connectionName)))
            {
                await connection.OpenAsync();
                using (SqlCommand command = new SqlCommand(sql, connection))
                {
                    return await command.ExecuteNonQueryAsync();
                }
            }
        }

        [ExportMethod("Select")]
        public async Task<DataTable?> SelectAsync(string sql, string connectionName)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(this.configuration.GetConnectionString(connectionName)))
                {
                    await connection.OpenAsync();
                    using (SqlCommand command = new SqlCommand(sql, connection))
                    {
                        var reader = await command.ExecuteReaderAsync();
                        DataTable dt = new DataTable();
                        dt.Load(reader);
                        return dt;
                    }
                }
            }
            catch (Exception ex)
            {
                _ = ex;
                return null;
            }
        }

    }

}